package model

import (
	"fmt"
	"github.com/go-xorm/xorm"
	_ "github.com/lib/pq"
	"lab-service/config"
	"log"
)

var orm *xorm.Engine

func init() {
	orm = dbConn()
}

func dbConn() *xorm.Engine {
	cfg := config.GetConfig().Database
	dbStr := fmt.Sprintf("host=%s port=%d user=%s dbname=%s sslmode=disable password=%s",
		cfg.Address, cfg.Port, cfg.User, cfg.Name, cfg.Pass)
	engine, err := xorm.NewEngine("postgres", dbStr)
	if err != nil {
		log.Fatal(err)
	}
	//defer orm.Close()
	err = engine.Sync2(
		new(Post),
		new(Message),
		new(Notice),
	)
	if err != nil {
		log.Fatal(err)
	}
	return engine
}

func Orm() *xorm.Engine {
	if orm == nil || orm.DB().Ping() != nil {
		orm = dbConn()
	}
	return orm
}
